from typing import Optional, List

from peewee import Model, CharField, IntegerField, AutoField, FloatField
from playhouse.shortcuts import model_to_dict
from pydantic import BaseModel

from db.my_sqlite import DB


# 定义文件模型
class Feedback(Model):
    id = AutoField(primary_key=True, help_text="反馈id")
    userid = IntegerField(help_text="用户id")
    rating = IntegerField(help_text="评价， 0：好，1：差")
    describe = CharField(help_text="描述")
    timestamp = FloatField(help_text="创建时间戳")
    query = CharField(help_text="问题")
    answer = CharField(help_text="回答")
    recommend = CharField(help_text="推荐问题")
    source = CharField(help_text="来源列表")

    class Meta:
        database = DB


class FeedbackModel(BaseModel):
    id: Optional[int]
    userid: Optional[int]
    rating: Optional[int]
    describe: Optional[str]
    timestamp: Optional[float]
    query: Optional[str]
    answer: Optional[str]
    recommend: Optional[str]
    source: Optional[str]

class FeedbackTable:
    def __init__(self, db):
        self.db = db
        self.db.create_tables([Feedback])

    @staticmethod
    async def insert_new_feedback(
            userid: int,
            rating: int,
            describe: str,
            timestamp: float,
            query: str,
            answer: str,
            recommend: str,
            source: str,
    ) -> Optional[FeedbackModel]:
        file = Feedback.create(
            userid=userid,
            rating=rating,
            describe=describe,
            timestamp=timestamp,
            query=query,
            answer=answer,
            recommend=recommend,
            source=source
        )
        return FeedbackModel(**model_to_dict(file))


    @staticmethod
    def get_feedback_by_userid(userid: int) -> List[FeedbackModel]:
        files = Feedback.select().where(
            (Feedback.userid == userid)
        )

        return [FeedbackModel(**model_to_dict(file)) for file in files]


Feedbacks = FeedbackTable(DB)
